﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using SqlSugar;


namespace OpenAuth.App
{
    public class {ModuleCode} : SqlSugarBaseApp<{ClassName}>
    {

        /// <summary>
        /// 加载列表
        /// </summary>
        public async Task<TableData> Load(Query{ClassName}ListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            var columnFields = loginContext.GetTableColumns("{ClassName}");
            if (columnFields == null || columnFields.Count == 0)
            {
                throw new Exception("请在代码生成界面配置{ClassName}表的字段属性");
            }

            var result = new TableData();
            var objs = GetDataPrivilege("u");
            if (!string.IsNullOrEmpty(request.key))
            {
                //增加筛选条件,如：
                objs = objs.Where(u => u.Name.Contains(request.key));
            }

            {ForeignKeyTemplate}

            var columnnames = columnFields.Select(u => u.ColumnName);
            var propertyStr = string.Join(',', columnnames);
            result.columnFields = columnFields;
            result.data = objs.OrderByDescending(u => u.Id)
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).Select($"{propertyStr}").ToList();
            result.count = await objs.CountAsync();
            return result;
        }

        public void Add(AddOrUpdate{ClassName}Req req)
        {
            var obj = req.MapTo<{ClassName}>();
            obj.Id = Guid.NewGuid().ToString();
            //todo: 根据业务需要调整字段
            obj.Createtime = DateTime.Now;
            var user = _auth.GetCurrentUser().User;
            obj.Createuserid = user.Id;
            obj.Createusername = user.Name;
            Repository.Insert(obj);
        }

        public void Update(AddOrUpdate{ClassName}Req obj)
        {
            var user = _auth.GetCurrentUser().User;
            Repository.Update(u => new {ClassName}
            {
                //todo: 根据业务需要调整字段
                Name = obj.Name,
                Updatetime = DateTime.Now,
                Updateuserid = user.Id,
                Updateusername = user.Name
            },u => u.Id == obj.Id);

        }

        public {ModuleCode}(ISqlSugarClient client, IAuth auth) : base(client, auth)
        {
        }
    }
}